from goods.models import *
from django.core.files.storage import Storage
from django.conf import settings
from fdfs_client.client import Fdfs_client
from rest_framework import serializers


def get_menu():
    """查询商品三级目录函数"""
    good_all_kinds = GoodsChannel.objects.all().order_by("group_id", "sequence")
    # 查询出所有商品种类
    goods_dict = {}
    for good_channel in good_all_kinds:
        if good_channel.group_id not in goods_dict:
            # 有此频道就不再创建键值对    无此频道创建键值对
            goods_dict[good_channel.group_id] = {
                "cat1": [],  # 一级商品频道
                "cat2": [],  # 二级商品列表
            }
        goods_dict[good_channel.group_id]["cat1"].append(good_channel)
        # 添加一级目录数据

        good_cat2 = good_channel.category.subs.all().order_by("id")
        # 查询出当前一级目录下所有二级目录对象
        for goods in good_cat2:
            # goods 为二级商品
            goods_dict[good_channel.group_id]["cat2"].append(goods)

    return goods_dict


def storagePic(content):
    """连接fds并存入文件"""
    conn = Fdfs_client(settings.FILE_CONFIG)
    ret = conn.upload_by_buffer(content)

    return ret


class FileStorage(Storage):
    """重写django  Storage类"""
    def _open(self, name, mode='rb'):

        return None

    def _save(self, name, content):
        ret = storagePic(content.read())
        status = ret.get("Status")
        if status != 'Upload successed.':
            serializers.ValidationError("上传失败")
        return ret.get("Remote file_id")

    def url(self, name):
        return settings.FILEURL+name
        # _open()
        # 和_save()

    def exists(self, name):
        # 不用判断是否重复    fastdfs自带有判断重复功能
        return False
